const app = getApp()
const testUrl = 'http://192.168.101.142:8078/api/v1'
// const onlineUrl = 'http://120.78.228.50:8078/api/v1'

const onlineUrl = 'https://dm.okbounty.com/api/v1'
// 海报底图配置地址
const shareBgUrl = 'https://qushangstar.oss-cn-beijing.aliyuncs.com/resources/share_bg.jpg'
const qrImageUrl = 'https://qushangstar.oss-cn-beijing.aliyuncs.com/resources/qrcode.jpg'
// const url = testUrl
const url = onlineUrl
const AppID = 'wx46d5a1fcfed30727'
const AppSecret = 'd72e44b78aa6d65ff9dbe3fa10a70e87'
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const getPage = function (index) {
  return parseInt(index / 3)
}
const random = function (min, max) {
  // 若max不存在 min 赋值给max,并重新赋值min
  if (max == null) {
    max = min;
    min = 0;
  }
  return min + Math.floor(Math.random() * (max - min + 1))
}
const wxFormatCheck = t => {
  var matched = false
  if (t && (t = t.trim()), t) {
    if (/^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/.test(t)) matched = true;
  }
  return matched
}
const login = (loginDidResponse, didFaild, refereeId) => {
  wx.request({
    url: url+'/user/login', // 仅为示例，并非真实的接口地址
    method: 'POST',
    data: {
      "code": app.globalData.code,
      'refereeId': refereeId,
      'userInfo': {
        'nickname': app.globalData.userInfo.nickName,
        'sex': app.globalData.userInfo.gender,
        'avatar': app.globalData.userInfo.avatarUrl
      }
    },
    header: {
      'content-type': 'application/json' // 默认值
    },
    success(res) {
      if (loginDidResponse) {
        loginDidResponse(res.data)
      }
    },
    fail(res) {
      if (didFaild) {
        didFaild(res.data)
      }
    }
  })
}
const updateUserInfo = (requestDidResponse, requestDidFaild,updateInfo) => {
  var ticket = wx.getStorageSync('ticket')
  var stringfy = JSON.stringify(updateInfo)
  wx.request({
    url: url+'/user/updateUser', // 仅为示例，并非真实的接口地址
    method: 'POST',
    data: stringfy,
    header: {
      'content-type': 'application/json', // 默认值
      'ticket': ticket
    },
    success(res) {
      if (requestDidResponse) {
        requestDidResponse(res.data)
      }
    },
    fail(res) {
      if (requestDidFaild) {
        requestDidFaild(res.data)
      }
    }
  })
}
const getUserInfo = (requestDidResponse, requestDidFaild, id) => {
  var ticket = wx.getStorageSync('ticket')
  wx.request({
    url: url + '/user/getUser', // 仅为示例，并非真实的接口地址
    method: 'POST',
    data: {
      'id': id
    },
    header: {
      'content-type': 'application/json', // 默认值
      'ticket': ticket
    },
    success(res) {
      if (requestDidResponse) {
        requestDidResponse(res.data)
      }
    },
    fail(res) {
      if (requestDidFaild) {
        requestDidFaild(res.data)
      }
    }
  })
}
const getKeyWord = (data,requestDidResponse, requestDidFaild,obj) => {
  console.log('---------------')
  console.log(obj)
  console.log('---------------')

  var ticket = wx.getStorageSync('ticket')
  wx.request({
    url: url + '/user/getKeyWord', // 仅为示例，并非真实的接口地址
    method: 'POST',
    data: data,
    header: {
      'content-type': 'application/json', // 默认值
      'ticket': ticket
    },
    success(res) {
      if (requestDidResponse) {
        requestDidResponse.call(obj,res.data)
      }
    },
    fail(res) {
      if (requestDidFaild) {
        requestDidFaild.call(obj, res.data)
      }
    }
  })
}
const fileUpload = (requestDidResponse, requestDidFaild,filePath) => {
  var ticket = wx.getStorageSync('ticket')
  wx.uploadFile({
    // url: 'http://192.168.101.113:8081/url/upload', // 仅为示例，非真实的接口地址
    url: url +'/user/uploadImg', // 仅为示例，非真实的接口地址
    filePath: filePath,
    name: 'file',
    header: {
      "Content-Type": "multipart/form-data",
      'accept': 'application/json',
      'ticket': ticket    //若有token，此处换上你的token，没有的话省略
    },
    success(res) {
      if (requestDidResponse) {
        requestDidResponse(res.data)
      }
    },
    fail(res) {
      if (requestDidFaild) {
        requestDidFaild(res.data)
      }
    }
  })
}
const getPhoneNumber = (requestDidResponse, requestDidFaild, iv, encryptedData) => {
  var ticket = wx.getStorageSync('ticket')
  wx.request({
    url: url + '/user/wxDecrypt', // 仅为示例，并非真实的接口地址
    method: 'POST',
    data: { 'encrypted': encryptedData, 'iv': iv},
    header: {
      'content-type': 'application/json', // 默认值
      'ticket': ticket
    },
    success(res) {
      if (requestDidResponse) {
        requestDidResponse(res.data)
      }
    },
    fail(res) {
      if (requestDidFaild) {
        requestDidFaild(res.data)
      }
    }
  })
}
const getResult = (requestDidResponse, requestDidFaild) => {
  var ticket = wx.getStorageSync('ticket')
  wx.request({
    url: url + '/user/mateUserList', // 仅为示例，并非真实的接口地址
    method: 'POST',
    data: {},
    header: {
      'content-type': 'application/json', // 默认值
      'ticket': ticket
    },
    success(res) {
      if (requestDidResponse) {
        requestDidResponse(res.data)
      }
    },
    fail(res) {
      if (requestDidFaild) {
        requestDidFaild(res.data)
      }
    }
  })
}
const getCommonFriends = (requestDidResponse, requestDidFaild, id) => {
  var ticket = wx.getStorageSync('ticket')
  wx.request({
    url: url + '/user/commonFriends', // 仅为示例，并非真实的接口地址
    method: 'POST',
    data: {
      'id': id
    },
    header: {
      'content-type': 'application/json', // 默认值
      'ticket': ticket
    },
    success(res) {
      if (requestDidResponse) {
        requestDidResponse(res.data)
      }
    },
    fail(res) {
      if (requestDidFaild) {
        requestDidFaild(res.data)
      }
    }
  })
}
const downloadShareBg = (downloadSuccess,downloadFailed) => {
  wx.downloadFile({
    url: shareBgUrl, // 仅为示例，并非真实的资源
    success(res) {
      // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
      if (res.statusCode === 200) {
        console.log(res)
        if (downloadSuccess) {
          downloadSuccess(res)
        }
      }else{
        if (downloadFailed) {
          downloadFailed(res)
        }
      }
    },
    fail(res) {
      if (downloadFailed) {
        downloadFailed(res)
      }
    }
  })
}
const downloadQRImage = (downloadSuccess, downloadFailed) => {
  wx.downloadFile({
    url: qrImageUrl, // 仅为示例，并非真实的资源
    success(res) {
      // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
      if (res.statusCode === 200) {
        console.log(res)
        if (downloadSuccess) {
          downloadSuccess(res)
        }
      } else {
        if (downloadFailed) {
          downloadFailed(res)
        }
      }
    },
    fail(res) {
      if (downloadFailed) {
        downloadFailed(res)
      }
    }
  })
}
const getQrode = (didGetData,token) => {
  // 生成页面的二维码
  wx.request({
    url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + token,
    method: "POST",
    responseType: 'arraybuffer',  //设置响应类型
    data: {
      'scene':'haha',
      width:50
    },
    success(res) {
      console.log(res)
      var src2 = wx.arrayBufferToBase64(res.data);  //对数据进行转换操作
      if (didGetData) {
        didGetData(src2)
      }
    },
    fail(e) {
      console.log(e)
    } 
  })
}
const getSession = (didGetData) => {
  // 生成页面的二维码
  wx.request({
    url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + AppID + '&secret=' + AppSecret,
    method: "GET",
    success(res) {
      console.log(res)
      if (didGetData) {
        didGetData(res.data.access_token)
      }
    },
    fail(e) {
      console.log(e)
    }
  })
}
module.exports = {
  wxFormatCheck: wxFormatCheck,
  formatTime: formatTime,
  getPage: getPage,
  random: random,
  login: login,
  updateUserInfo: updateUserInfo,
  getKeyWord: getKeyWord,
  fileUpload: fileUpload,
  getPhoneNumber: getPhoneNumber,
  getUserInfo: getUserInfo,
  downloadShareBg: downloadShareBg,
  downloadQRImage: downloadQRImage,
  getResult: getResult,
  getCommonFriends: getCommonFriends,
  getQrode: getQrode,
  getSession: getSession
}
